<template>
  <div id="Panel">
    <panel-header
      :title="title"
      :operation="operation"
      :panelCharts="panelCharts"
      @selectChartHandle="selectChart"
      @saveHandle="saveHandle"
      @delChart="delChart"
    ></panel-header>
    <div style="height: 12px"></div>
    <el-row type="flex" :gutter="4" style="height: 92%">
      <el-col span="18">
        <router-view style="height: 60%"></router-view>
        <div style="height: 12px"></div>
        <sql-panel style="height: 38%"></sql-panel>
      </el-col>
      <el-col span="6">
        <select-panel-box></select-panel-box>
        <div style="height: 6px"></div>
        <panel-option style="height: 94%"></panel-option>
      </el-col>
    </el-row>
  </div>
</template>
<script>
import { request } from "../../utils/index.js";

import panelHeader from "./panelHeader.vue";
import selectPanelBox from "./selectPanelBox.vue";
import panelOption from "./panelOption.vue";
import sqlPanel from "./sqlPanel.vue";

export default {
  props: {},
  components: {
    panelHeader,
    selectPanelBox,
    panelOption,
    sqlPanel,
  },
  data() {
    return {
      title: "",
      operation: "添加",

      subSystemPath: "",
      panelId: NaN,
      panelCharts: [],
      editChartId: NaN,
    };
  },
  created() {
    this.subSystemPath = this.$route.params.subPath;
    const panelChartType = window.location.pathname.split("/").pop();
    this.$store.commit("setPanelPath", {
      panelName: panelChartType,
    });
    this.panelId = this.$route.query.panelId;
    this.getPanelCharts(this.panelId);
    this.getPanelInfo();

     // 清空数据
        this.$store.commit("setSQLData", {
          sqlStr: "",
          sqlParam: "",
          sqlData: [],
          sqlSource: {},
        });
  },
  mounted() {},
  watch: {
    "$store.state.addPanel.currentPanelName": {
      handler(val) {
        const newPathArr = this.$route.path.split("/");
        const lastType = newPathArr.pop();
        if (lastType !== val) {
          newPathArr.push(val);
          const newPath = newPathArr.join("/");
          this.$router.replace({
            path: newPath,
            query: this.$route.query,
          });
        }
      },
    },
  },
  methods: {
    saveHandle() {
      if (this.operation === "添加") {
        this.createChart();
      } else {
        this.editChart(this.editChartId);
      }
    },
    // 获取子系统面板
    getPanelCharts(panelId) {
      const reqPanelId = panelId || this.panelId;
      return request({
        method: "GET",
        url: `/public/panel/getcharts/${reqPanelId}`,
        params: {},
      }).then((res) => {
        this.panelCharts = res.result.map((item) => {
          const newchartJson = JSON.parse(item.chartJson);
          const title = newchartJson?.baseOption?.title.text;
          return {
            ...item,
            chartName: title,
            optionInfo: newchartJson,
          };
        });
      });
    },

    async selectChart(chartId) {
      if (chartId !== "add" && chartId) {
        // 走编辑逻辑
        this.operation = "编辑";
        this.editChartId = chartId;
        const editChartInfo = this.panelCharts.find(
          (item) => item.chartId === chartId
        );
        const { chartType, optionInfo = {}, chartHTML } = editChartInfo;
        const { extInfo, baseOption } = optionInfo;

        const {
          result: { dataSourceId, sql, ortherData },
        } = await this.getChartSQL(chartId);
        const { result: sqlData } = await this.getSQLData({
          dataSourceId,
          ortherData,
          sql,
          chartId,
        });
        // console.log("zct sql",sql)
        // 处理SQL数据
        this.$store.commit("setSQLData", {
          sqlStr: sql,
          sqlParam: ortherData,
          sqlSource: { dataSourceId },
          sqlData: sqlData,
        });

        if (extInfo) {
          // 处理XY轴
          this.$store.commit("setTableShowXYData", {
            selectPanelData: {
              x: extInfo.x,
              y: extInfo.y,
            },
          });
        }

        // 处理表格类型
        this.$store.commit("setPanelPath", {
          panelName: chartType,
        });
        console.log("zct baseOption",baseOption)
        // 根据不同的表格类型修改对应的baseOption
        this.$store.commit("changeTypeOption", { baseOption, chartType });

        // 处理转换方法
        if (chartHTML) {
          const funBody = chartHTML.split("handler(data)")[1].trim();
          if (funBody) {
            const fun = new Function("data", funBody);
            const dataRes = fun(sqlData);

            this.$store.commit("setSQLHandleData", {
              sqlHandle: chartHTML,
              sqlHandleData: dataRes,
            });
          }
        }
      } else {
        // 走新增逻辑
        this.operation = "添加";
        this.editChartId = NaN;
        // 清空数据
        this.$store.commit("setSQLData", {
          sqlStr: "",
          sqlParam: "",
          sqlData: [],
          sqlSource: {},
        });
        // 处理表格类型
        this.$store.commit("setPanelPath", {
          panelName: "table",
        });
        // 处理XY轴
        this.$store.commit("setTableShowXYData", {
          selectPanelData: {
            x: undefined,
            y: undefined,
          },
        });
      }
    },

    getPanelInfo() {
      return request({
        method: "GET",
        url: this.portInterface.getPanelInfo + this.panelId,
      }).then((res) => {
        this.title = res.result.panelTitle;
      });
    },

    getSQLParams(chartId) {
      return request({
        method: "GET",
        url: this.portInterface.getSQLParams + this.panelId,
        params: { chartId },
      });
    },

    getChartSQL(chartId) {
      return request({
        method: "GET",
        url: this.portInterface.getChartSQL + this.panelId,
        params: {
          chartId: chartId,
        },
      });
    },

    getSQLData(params) {
      const { dataSourceId, ortherData, sql, chartId } = params;
      return request({
        method: "POST",
        url: this.portInterface.getDataBySQL,
        data: {
          chartId,
          dataSourceId,
          ortherData,
          sql,
        },
      });
    },

    // 编辑面板
    async editChart(chartId) {
      try {
        const reqChartParams = this.$store.getters.getReqChartParams;
        const reqSQLParams = this.$store.getters.getReqSQLParams;

        await request({
          method: "PUT",
          url: this.portInterface.updateChart + this.panelId,
          data: {
            ...reqChartParams,
            chartId,
          },
        });

        await request({
          method: "PUT",
          url: this.portInterface.updateChartSQL + this.panelId,
          data: {
            ...reqSQLParams,
            chartId,
          },
        });
        this.$message({
          showClose: true,
          message: "编辑成功",
          type: "success",
        });
        this.getPanelCharts(this.panelId);
      } catch (error) {
        console.error(error);
        this.$message({
          showClose: true,
          message: "编辑失败",
          type: "error",
        });
      }
    },

    // 添加面板图表
    async createChart() {
      try {
        const reqChartParams = this.$store.getters.getReqChartParams;
        const reqSQLParams = this.$store.getters.getReqSQLParams;

        const { result: chartRes } = await request({
          method: "POST",
          url: this.portInterface.addChart + this.panelId,
          data: reqChartParams,
        });
        const chartId = chartRes.chartId;

        await request({
          method: "POST",
          url: this.portInterface.addChartSQL + this.panelId,
          data: {
            ...reqSQLParams,
            chartId,
          },
        });
        this.$message({
          showClose: true,
          message: "添加成功",
          type: "success",
        });
        this.getPanelCharts();
      } catch (error) {
        console.error(error);
        this.$message({
          showClose: true,
          message: "添加失败",
          type: "error",
        });
      }
    },
    // 删除图表
    delChart(chartId) {
      let p1 = request({
        method: "DELETE",
        url: this.portInterface.delChart + this.panelId,
        params: {
          chartId,
        },
      });
      let p2 = request({
        method: "DELETE",
        url: this.portInterface.delChartSQL + this.panelId,
        params: {
          chartId,
        },
      });
      Promise.all([p1, p2])
        .then(() => {
          this.$message({
            showClose: true,
            message: "删除成功",
            type: "success",
          });
          this.getPanelCharts();
        })
        .catch((error) => {
          console.error(error);
          this.$message({
            showClose: true,
            message: "删除失败",
            type: "error",
          });
        });
    },
  },
};
</script>
<style scoped>
#Panel {
  padding: 0 12px;
  height: 100%;
  overflow: hidden;
}
</style>
